package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.*;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.feign.UserFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.service.MinIOService;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author lqw
 * @since 2022-06-23
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
    @Autowired
    private IApArticleContentService apArticleContentService;
    @Autowired
    private ITemplateService templateService;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IApCollectionService collectionService;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private IApAuthorService apAuthorService;
    @Autowired
    private IApCollectionService apCollectionService;

    /**
     * 存储已发布的文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        // 需求分析
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        // 判断dto中id是否为空
        if (dto.getId() == null) {
            // id为空 新增文章
            // 保存文章表
            article.setId(null);
            article.setCreatedTime(new Date());
            this.save(article);
            // 保存内容表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(dto.getId());
            apArticleContent.setContent(dto.getContent());

            apArticleContentService.save(apArticleContent);
            // 生成静态html  需要异步处理
            System.out.println(Thread.currentThread().getName() + " 开始调用生成静态html服务...");
            templateService.createHtml(article, dto.getContent());
            System.out.println(Thread.currentThread().getName() + "生成静态html服务结束");
            // 返回通用的响应
            return ResponseResult.okResult(article.getId());
        } else {
            // id不为空,修改文章
            this.updateById(article);
            // 修改内容表
            LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
            update.eq(ApArticleContent::getArticleId, dto.getId());
            update.set(ApArticleContent::getContent, dto.getContent());
            apArticleContentService.update(update);
            //todo 生成静态页面
            System.out.println(Thread.currentThread().getName() + " 开始调用生成静态html服务...");
            //删除之前的静态HTML
            if (!StringUtils.isEmpty(article.getStaticUrl())) {
                minIOService.delete(article.getStaticUrl());
            }
            templateService.createHtml(article, dto.getContent());
            System.out.println(Thread.currentThread().getName() + "生成静态html服务结束");
            return ResponseResult.okResult(article.getId());
        }
    }


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 加载首页文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        // 判断是否是首页加载数据,如果是首页的话,先从redis中查询数据
        if (dto.getLoaddir() == 1) {
            //是首页
            String key = "hot_article_" + dto.getChannelId();
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(key, 0, dto.getSize() - 1);
            List<ArticleCache> list = new ArrayList<>();
            for (String string : strings) {
                ArticleCache articleCache = JSON.parseObject(string, ArticleCache.class);
                list.add(articleCache);
            }
            //如果redis缓存数据够一页展示则走缓存,不走数据库
            if (list.size() == dto.getSize()) {
                return ResponseResult.okResult(list);
            }

        }


        //构建查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        //当前端传来频道,添加频道条件
        if (dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        //展示最新内容    添加查询条件:发布时间大于页面传递的最大时间
        if (dto.getLoaddir() == 0) {
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }
        //展示历史更多内容    添加查询条件:发布时间小于页面传递最小时间
        if (dto.getLoaddir() == 2) {
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        //不展示已下架或者已删除的文章
        query.eq(ApArticle::getIsDelete, false);
        query.eq(ApArticle::getIsDown, false);
        // 文章列表按照发布时间倒序排列
        query.orderByDesc(ApArticle::getPublishTime);
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        IPage<ApArticle> iPage = this.page(page, query);
        return ResponseResult.okResult(iPage.getRecords());
    }

    /**
     * 加载文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        ApArticle article = this.getById(dto.getArticleId());
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent articleContent = apArticleContentService.getOne(query);
        Map<String, Object> map = new HashMap<>();
        map.put("config", article);
        map.put("content", articleContent);
        return ResponseResult.okResult(map);
    }

    /**
     * 文章收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            //没登陆
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApCollection apCollection = new ApCollection();
        apCollection.setEntryId(user.getUserId());
        apCollection.setArticleId(dto.getArticleId());
        apCollection.setCollectionTime(new Date());
        //查询该用户之前是否有过收藏该文章的记录
        LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
        query.eq(ApCollection::getEntryId, user.getUserId())
                .eq(ApCollection::getArticleId, dto.getArticleId());
        ApCollection one = collectionService.getOne(query);
        if (one == null) {
            //无记录
            if (dto.getOperation() == 0)
                collectionService.save(apCollection);
            // 发送收藏消息到kafka
                sendMessage(dto);
        } else {
            if (dto.getOperation() == 1) {
                //取消收藏,删除收藏记录
                collectionService.removeById(one.getId());
                // 发送收藏消息到kafka
                sendMessage(dto);
            }
        }
        //发消息到Kafka

        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Value("${topic.collect_behavior}")
    private String collectTopic;
    /**
     * 发消息到Kafka
     * @param dto
     */
    private void sendMessage(CollectionBehaviorDto dto) {
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setType(3);
        message.setArticleId(dto.getArticleId());
        if (dto.getOperation() == 1){
            message.setAdd(-1);
        }else {
            message.setAdd(1);
        }
        String json = JSON.toJSONString(message);
        kafkaTemplate.send(collectTopic,json);
    }

    /**
     * 加载文章行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //判断用户是否登录
        User user = AppThreadLocalUtil.get();
        //定义是否关注的属性
        Boolean isfollow = false;
        Boolean iscollection = false;
        Boolean islike = false;
        Boolean isunlike = false;
        if (user != null) {
            //用户登录
            //1.是否关注作者
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setUserId(user.getUserId());
            //根据文章id查询用户id
            ApAuthor author = apAuthorService.getById(dto.getAuthorId());
            followBehaviorDto.setFollowId(author.getUserId());
            ResponseResult<ApUserFollow> follow = userFeign.getFollow(followBehaviorDto);
            if (follow.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                ApUserFollow followData = follow.getData();
                if (followData != null) {
                    isfollow = true;
                }
            }
            //2.是否收藏
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
            query.eq(ApCollection::getArticleId, dto.getArticleId());
            query.eq(ApCollection::getEntryId, user.getUserId());
            ApCollection one = apCollectionService.getOne(query);
            if (one != null) {
                //收藏 ,设为true
                iscollection = true;
            }
        }

        //3.是否点赞
        LikesBehaviorDto likesBehaviorDto = new LikesBehaviorDto();
        likesBehaviorDto.setArticleId(dto.getArticleId());
        if (user == null) {
            //未登录
            likesBehaviorDto.setEquipmentId(dto.getEquipmentId());
        } else {
            likesBehaviorDto.setUserId(user.getUserId());
        }
        ResponseResult<ApLikesBehavior> likes = behaviorFeign.getLikes(likesBehaviorDto);

        if (likes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApLikesBehavior likesBehavior = likes.getData();
            if (likesBehavior != null && likesBehavior.getOperation() == 0) {
                islike = true;
            }
        }
        //4.是否不喜欢
        UnLikesBehaviorDto unlikesBehaviorDto = new UnLikesBehaviorDto();
        unlikesBehaviorDto.setArticleId(dto.getArticleId());
        if (user == null) {
            unlikesBehaviorDto.setEquipmentId(dto.getEquipmentId());
        } else {
            unlikesBehaviorDto.setUserId(user.getUserId());
        }
        ResponseResult<ApUnlikesBehavior> unlikes = behaviorFeign.getUnlikes(unlikesBehaviorDto);
        if (unlikes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUnlikesBehavior unlikesBehavior = unlikes.getData();
            if (unlikesBehavior != null && unlikesBehavior.getType() == 0) {
                isunlike = true;
            }
        }
        //创建返回数据
        Map<String, Boolean> result = new HashMap<>();
        result.put("isfollow", isfollow);
        result.put("iscollection", iscollection);
        result.put("islike", islike);
        result.put("isunlike", isunlike);
        return ResponseResult.okResult(result);
    }

}
